package com.zyb.patient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;

import com.zyb.patient.service.DbSqliteService;
import com.zyb.patient.service.MainService;
import com.zyb.patient.util.CrashUtil;
import com.zyb.patient.util.LogUtil;


public class ZybApplication extends Application {
    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        String processName = getProcessName(this, android.os.Process.myPid());
        if (processName != null) {
            boolean defaultProcess = processName.equals(this.getPackageName());
            if (defaultProcess) {//本进程
                initAppForMainProcess();
            }else{
                //其它进程
            }
        }
    }
    
    /*** 本进程初始化  ***/
    private void initAppForMainProcess(){
        initSQLAndIcon();
        initService();
        initCrashWork();
    }
    
    /**
     * 启动后台Service
     * 
     */
    private void initService() {
        /**  my service **/
        Intent service = new Intent(this, MainService.class);
        startService(service);

//        /** push service **/
//        try {
//            if (mContext != null) {
//                String metaValue = AppUtils.getMetaValue(mContext, "api_key");
//                if (metaValue != null) {
//                    PushManager.startWork(mContext, PushConstants.LOGIN_TYPE_API_KEY, metaValue);
//                }
//            }
//        } catch (Exception e) {
//            LogUtil.e(e.toString());
//        }
    }

    /***
     * 首次安装创建数据库
     * ***/
    private void initSQLAndIcon() {
        /*** device ***/
        DbSqliteService db = new DbSqliteService(this);
        String dbVersion = db.getConfigItem("dbversion");
        if (null == dbVersion) {
            try {
                createIcon();
                db.createDataBase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 自动创建桌面图标
     * ***/
    public void createIcon() {
        Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
        // intent.putExtra("duplicate" , false);
        Intent intent2 = new Intent(Intent.ACTION_MAIN);
        intent2.addCategory(Intent.CATEGORY_LAUNCHER);
        // ComponentName(this.getPackageName() ,
        // "com.ss.view.LoadingActivity"));
        intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher));
        sendBroadcast(intent);
    }
    /** 开始获取版本信息 **/
    /*private void getNewVersion() {
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
    map.put("command", "upgrade");
    map.put("version_id", AppUtils.getVerName(Constant.PACKAGE, mContext));
    Task task = new Task(Task.GET_VERSION2, map);
    MainService.newTask(task);
    }*/

    private void initCrashWork() {
        CrashUtil.getInstance().startWork();
    }

    /**
     * @return null may be returned if the specified process not found
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

    public void getSingInfo() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo("com.kz.activity",
                    PackageManager.GET_SIGNATURES);
            Signature[] signs = packageInfo.signatures;
            Signature sign = signs[0];
            parseSignature(sign.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void parseSignature(byte[] signature) {
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate) certFactory
                    .generateCertificate(new ByteArrayInputStream(signature));
            String pubKey = cert.getPublicKey().toString();
            String signNumber = cert.getSerialNumber().toString();
            LogUtil.e("pubKey:" + pubKey);
            LogUtil.e("signNumber:" + signNumber);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
    }

}